export class UIController {
    constructor() {
        this.elements = {
            totalCard: '#total-card',
            rankCard: '#rank-card',
            totalComparison: '#total-comparison',
            rankComparison: '#rank-comparison',
            showTotal: '#show-total',
            showRank: '#show-rank',
            apiTotalStat: '#api-total-stat',
            dbTotalStat: '#db-total-stat',
            matchRateStat: '#match-rate-stat',
            seriesFilter: '#series-filter',
            modal: '#dbDataModal',
            tableHeaders: '#table-headers',
            tableBody: '#table-body',
            modalTitle: '.modal-title',
            iframeContainer: '#iframe-container',
            tableContainer: '#table-container',
            externalPage: '#external-page'
        };
    }

    getElement(selector) {
        return document.querySelector(selector);
    }

    updateVisibility() {
        const showTotal = this.getElement(this.elements.showTotal).checked;
        const showRank = this.getElement(this.elements.showRank).checked;
        
        const totalCard = this.getElement(this.elements.totalCard);
        const rankCard = this.getElement(this.elements.rankCard);
        
        if (totalCard) {
            totalCard.style.display = showTotal ? 'block' : 'none';
        }
        
        if (rankCard) {
            rankCard.style.display = showRank ? 'block' : 'none';
        }

        // 获取最后一次更新的数据
        const lastData = this._lastData;
        if (lastData) {
            // 更新匹配率统计
            this.updateStatsPanel(lastData);
        }
    }

    updateTotalComparison(data) {
        const container = this.getElement(this.elements.totalComparison);
        if (!container) return;
        
        if (data.error) {
            container.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
            return;
        }
        
        // 保存最后一次更新的数据，用于显示控制时重新计算匹配率
        this._lastData = data;
        
        container.innerHTML = this.generateTotalComparisonHTML(data);
        this.updateStatsPanel(data);
    }

    // 添加一个计算颜色的方法
    getMatchRateColor(rate) {
        if (rate === 100) {
            return '#28a745';  // 绿色
        } else {
            // 使用 HSL 颜色空间来实现更好的渐变效果
            // hue: 0 是红色
            // saturation: 保持在 70%
            // lightness: 根据匹配率调整亮度，匹配率越低越深
            const hue = 0;  // 红色
            const saturation = 70;  // 70% 饱和度
            const lightness = 30 + (rate / 100) * 40;  // 亮度从 30% 到 70%
            return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
        }
    }

    updateStatsPanel(data) {
        // 初始化匹配项计数
        let matchedItems = 0;
        let totalItems = 0;

        // 检查总人数是否匹配
        if (data && data.api_total !== undefined && data.db_total !== undefined) {
            totalItems++;
            if (data.api_total === data.db_total) {
                matchedItems++;
            }
        }

        // 检查平均年龄是否匹配
        if (data && data.api_avg_age !== undefined && data.db_avg_age !== undefined) {
            totalItems++;
            const ageDiff = Math.abs(data.api_avg_age - data.db_avg_age);
            // 年龄差异保留一位小数，如果差异小于等于0.1岁则认为匹配
            if (Number(ageDiff.toFixed(1)) <= 0.1) {
                matchedItems++;
            }
        }

        // 检查职级分布是否匹配
        if (data && data.rank_data) {
            const rankData = data.rank_data;
            const allSeries = ['P序列', 'M序列', 'B序列'];
            
            allSeries.forEach(series => {
                // 获取API和数据库中该序列的所有职级
                const apiLevels = rankData.api_data?.[series] ? Object.keys(rankData.api_data[series]) : [];
                const dbLevels = rankData.db_data?.[series] ? Object.keys(rankData.db_data[series]) : [];
                
                // 合并所有出现的职级
                const allLevels = new Set([...apiLevels, ...dbLevels]);
                
                // 检查每个职级的匹配情况
                allLevels.forEach(level => {
                    totalItems++;
                    const apiCount = rankData.api_data?.[series]?.[level] || 0;
                    const dbCount = rankData.db_data?.[series]?.[level] || 0;
                    if (apiCount === dbCount) {
                        matchedItems++;
                    }
                });
            });
        }

        // 计算匹配率
        const matchRate = totalItems > 0 ? ((matchedItems / totalItems) * 100).toFixed(1) : '0.0';
        
        // 更新匹配率显示
        const matchRateElement = document.getElementById('match-rate-stat');
        if (matchRateElement) {
            matchRateElement.innerHTML = `
                <div class="match-rate-container">
                    <div class="match-rate-value">${matchRate}%</div>
                    <div class="match-rate-detail">
                        <i class="fas fa-check-circle"></i>
                        <span>${matchedItems}/${totalItems}项匹配</span>
                    </div>
                </div>
            `;
        }

        // 更新API总数和数据库总数的显示
        const apiTotalStat = this.getElement('#api-total-stat');
        if (apiTotalStat) {
            apiTotalStat.innerHTML = `
                <a href="#" class="view-api-details">
                    <i class="fas fa-external-link-alt me-2"></i>
                    <span>组织分析详情</span>
                </a>
            `;
            
            const apiDetailsLink = apiTotalStat.querySelector('.view-api-details');
            if (apiDetailsLink) {
                apiDetailsLink.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.showModal('组织分析详情');
                    this.getApiPersonnelData('all', 'all').then(data => {
                        this.displayTableData(data);
                    });
                });
            }
        }
        
        const dbTotalStat = this.getElement('#db-total-stat');
        if (dbTotalStat) {
            dbTotalStat.innerHTML = `
                <a href="#" class="view-db-details">
                    <i class="fas fa-external-link-alt me-2"></i>
                    <span>数据库人员信息</span>
                </a>
            `;
            
            const dbDetailsLink = dbTotalStat.querySelector('.view-db-details');
            if (dbDetailsLink) {
                dbDetailsLink.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.showModal('数据库人员信息');
                    this.getDbPersonnelData('all', 'all').then(data => {
                        this.displayTableData(data);
                    });
                });
            }
        }
    }

    generateTotalComparisonHTML(data) {
        return `
            <div class="table-responsive">
                <table class="table table-bordered table-hover comparison-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-list-ul me-2"></i>对比项</th>
                            <th><i class="fas fa-cloud me-2"></i>API数据</th>
                            <th><i class="fas fa-database me-2"></i>数据库数据</th>
                            <th><i class="fas fa-exchange-alt me-2"></i>差异</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 总人数对比 -->
                        <tr class="table-secondary">
                            <td colspan="4"><strong>总人数</strong></td>
                        </tr>
                        <tr class="${data.matched ? '' : 'table-warning'}">
                            <td>总人数</td>
                            <td>${data.api_total || 0}人</td>
                            <td>${data.db_total || 0}人</td>
                            <td>
                                <span class="difference-badge ${data.matched ? 'success' : 'danger'}">
                                    ${data.matched ? '无差异' : `差异: ${Math.abs((data.api_total || 0) - (data.db_total || 0))}人`}
                                </span>
                            </td>
                        </tr>
                        
                        <!-- 平均年龄对比 -->
                        <tr class="table-secondary">
                            <td colspan="4"><strong>平均年龄</strong></td>
                        </tr>
                        <tr class="${data.age_matched ? '' : 'table-warning'}">
                            <td>平均年龄</td>
                            <td>${data.api_avg_age || 0}岁</td>
                            <td>${Number(data.db_avg_age || 0).toFixed(1)}岁</td>
                            <td>
                                <span class="difference-badge ${data.age_matched ? 'success' : 'danger'}">
                                    ${data.age_matched ? '无差异' : `差异: ${Math.abs(data.api_avg_age - data.db_avg_age).toFixed(1)}岁`}
                                </span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        `;
    }

    showLoadingSpinner(container) {
        if (!container) return;
        
        container.innerHTML = `
            <div class="loading-container">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载数据...</div>
            </div>
        `;
    }

    showModal(title) {
        const modalElement = this.getElement(this.elements.modal);
        
        // 确保移除可能存在的旧遮罩
        const backdrop = document.querySelector('.modal-backdrop');
        if (backdrop) {
            backdrop.remove();
        }
        document.body.classList.remove('modal-open');
        
        const modal = new bootstrap.Modal(modalElement, {
            backdrop: 'static',
            keyboard: false
        });
        
        // 确保表格容器可见
        this.getElement(this.elements.iframeContainer).style.display = 'none';
        this.getElement(this.elements.tableContainer).style.display = 'block';
        
        // 设置标题
        const titleElement = this.getElement(this.elements.modalTitle);
        titleElement.innerHTML = title;

        // 添加新增按钮（如果不存在且不是组织分析详情页面）
        const modalHeader = modalElement.querySelector('.modal-header');
        const isOrganizationAnalysis = title.includes('组织分析详情');
        
        // 先移除已存在的新增按钮（如果有）
        const existingAddBtn = modalHeader.querySelector('.add-btn');
        if (existingAddBtn) {
            existingAddBtn.remove();
        }
        
        // 如果不是组织分析详情页面，则添加新增按钮
        if (modalHeader && !isOrganizationAnalysis) {
            const addButton = document.createElement('button');
            addButton.className = 'btn btn-success btn-sm ms-auto me-2 add-btn';
            addButton.innerHTML = '<i class="fas fa-plus"></i> 新增';
            addButton.onclick = () => this.showAddForm();
            
            // 将按钮插入到关闭按钮之前
            const closeButton = modalHeader.querySelector('.btn-close');
            modalHeader.insertBefore(addButton, closeButton);
        }
        
        // 添加关闭事件监听器
        modalElement.addEventListener('hidden.bs.modal', () => {
            // 移除模态窗口的遮罩和相关类
            const backdrop = document.querySelector('.modal-backdrop');
            if (backdrop) {
                backdrop.remove();
            }
            document.body.classList.remove('modal-open');
            document.body.style.overflow = '';
            document.body.style.paddingRight = '';
        });
        
        modal.show();
        return modal;
    }

    updateModalContent(data) {
        const tableHeaders = this.getElement(this.elements.tableHeaders);
        const tableBody = this.getElement(this.elements.tableBody);
        
        if (data.error) {
            tableBody.innerHTML = `<tr><td colspan="100%" class="text-danger">加载失败: ${data.error}</td></tr>`;
            return;
        }
        
        if (!data.data || !data.data.length) {
            tableBody.innerHTML = '<tr><td colspan="100%" class="text-center">暂无数据</td></tr>';
            return;
        }
        
        // 生成表头
        const headers = Object.keys(data.data[0]);
        tableHeaders.innerHTML = headers.map(header => 
            `<th scope="col" data-field="${header}">${header}</th>`
        ).join('');
        
        // 生成表体
        tableBody.innerHTML = data.data.map(row => `
            <tr>
                ${headers.map(header => 
                    `<td data-field="${header}" title="${row[header] || ''}">${row[header] || ''}</td>`
                ).join('')}
            </tr>
        `).join('');
    }

    updateRankComparison(data, selectedSeries = 'P序列') {
        const container = this.getElement(this.elements.rankComparison);
        if (!container) return;
        
        // 检查数据格式
        if (!data || !data.data) {
            container.innerHTML = `<div class="alert alert-danger">暂无数据</div>`;
            return;
        }
        
        // 获取API和数据库数据
        const apiData = data.data.api_data || {};
        const dbData = data.data.db_data || {};
        
        // 创建表格HTML
        let html = `
            <div class="table-responsive">
                <table class="table table-bordered table-hover comparison-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-layer-group me-2"></i>职级</th>
                            <th><i class="fas fa-cloud me-2"></i>API数据</th>
                            <th><i class="fas fa-database me-2"></i>数据库数据</th>
                            <th><i class="fas fa-exchange-alt me-2"></i>差异</th>
                        </tr>
                    </thead>
                    <tbody>
        `;
        
        // 处理选中的序列
        const seriesToShow = selectedSeries === 'all' ? ['P序列', 'M序列', 'B序列'] : [selectedSeries];
        
        // 遍历每个序列
        seriesToShow.forEach(series => {
            // 添加序列标题行
            html += `
                <tr class="table-secondary">
                    <td colspan="4"><strong>${series}</strong></td>
                </tr>
            `;
            
            // 获取当前序列的API和数据库数据
            const seriesApiData = apiData[series] || {};
            const seriesDbData = dbData[series] || {};
            
            // 获取所有职级
            const levels = {
                'P序列': ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8'],
                'M序列': ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9'],
                'B序列': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7']
            }[series] || [];
            
            if (levels.length === 0) {
                html += `
                    <tr>
                        <td colspan="4" class="text-center">暂无数据</td>
                    </tr>
                `;
            } else {
                // 遍历所有职级
                levels.forEach(level => {
                    const apiCount = seriesApiData[level] || 0;
                    const dbCount = seriesDbData[level] || 0;
                    const difference = Math.abs(apiCount - dbCount);
                    const isDifferent = apiCount !== dbCount;
                    
                    html += `
                        <tr class="${isDifferent ? 'table-warning' : ''} rank-row" data-series="${series}" data-level="${level}">
                            <td class="rank-cell">${level}</td>
                            <td class="clickable rank-data" data-type="api" data-count="${apiCount}">${apiCount}人</td>
                            <td class="clickable rank-data" data-type="db" data-count="${dbCount}">${dbCount}人</td>
                            <td>
                                <span class="difference-badge ${isDifferent ? 'danger' : 'success'}">
                                    ${isDifferent ? `差异: ${difference}人` : '无差异'}
                                </span>
                            </td>
                        </tr>
                    `;
                });
            }
        });
        
        html += `
                    </tbody>
                </table>
            </div>
        `;
        
        container.innerHTML = html;

        // 添加点击事件处理
        container.querySelectorAll('.clickable').forEach(cell => {
            cell.style.cursor = 'pointer';
            cell.addEventListener('click', async () => {
                const row = cell.closest('tr');
                const series = row.dataset.series;
                const level = row.dataset.level;
                const type = cell.dataset.type;
                const count = cell.dataset.count;

                // 显示加载中的模态窗
                const modal = this.showModal(`
                    <i class="fas fa-users me-2"></i>
                    ${series} - ${level} 人员详情 (${type === 'api' ? 'API数据' : '数据库数据'})
                    <div class="query-time ms-3">
                        <small class="text-muted">
                            <i class="fas fa-users me-1"></i>共 ${count} 人
                        </small>
                    </div>
                `);

                try {
                    // 根据类型获取不同的数据
                    const data = type === 'api' ? 
                        await this.getApiPersonnelData(series, level) :
                        await this.getDbPersonnelData(series, level);
                    
                    this.displayTableData(data);
                } catch (error) {
                    console.error('加载人员数据失败:', error);
                    this.showError('加载数据失败: ' + error.message);
                }
            });
        });
    }

    async getApiPersonnelData(series, level) {
        try {
            const url = series === 'all' && level === 'all' ? 
                '/api/api-data' : 
                `/api/personnel/api?series=${encodeURIComponent(series)}&level=${encodeURIComponent(level)}`;

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('获取API人员数据失败');
            }

            const result = await response.json();
            return result.data || [];
        } catch (error) {
            console.error('获取API人员数据失败:', error);
            throw error;
        }
    }

    async getDbPersonnelData(series, level) {
        try {
            const url = series === 'all' && level === 'all' ? 
                '/api/db/data' : 
                `/api/personnel/db?series=${encodeURIComponent(series)}&level=${encodeURIComponent(level)}`;

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('获取数据库人员数据失败');
            }

            const result = await response.json();
            return result.data || [];
        } catch (error) {
            console.error('获取数据库人员数据失败:', error);
            throw error;
        }
    }

    showExternalPage(url) {
        // 先显示模态窗
        const modal = this.showModal('组织画像数据');
        
        // 隐藏表格容器，显示iframe容器
        this.getElement(this.elements.tableContainer).style.display = 'none';
        const iframeContainer = this.getElement(this.elements.iframeContainer);
        iframeContainer.style.display = 'block';
        
        // 设置iframe的src
        const iframe = this.getElement(this.elements.externalPage);
        iframe.src = url;
        
        return modal;
    }

    showTableContainer() {
        this.getElement(this.elements.iframeContainer).style.display = 'none';
        this.getElement(this.elements.tableContainer).style.display = 'block';
    }

    displayTableData(data) {
        console.log('Displaying table data:', data);
        
        // 判断是否为 API 数据（通过模态框标题判断）
        const modalTitle = this.getElement(this.elements.modalTitle);
        const isApiData = modalTitle && modalTitle.textContent.includes('API数据');
        
        // 根据数据类型选择要显示的表头
        const headers = isApiData ? 
            ['ID', '姓名', '职级', '性别', '员工工号', '职位', '入职日期', '状态'] :
            ['ID', '姓名', '职级', '性别', '员工工号', '职位', '入职日期', '状态', '操作'];
            
        const tableHeaders = document.getElementById('table-headers');
        const tableBody = document.getElementById('table-body');
        
        // 清空现有内容
        tableHeaders.innerHTML = '';
        tableBody.innerHTML = '';
        
        // 添加表头
        headers.forEach(header => {
            const th = document.createElement('th');
            th.textContent = header;
            tableHeaders.appendChild(th);
        });
        
        // 如果没有数据，显示提示信息
        if (!data || !Array.isArray(data) || data.length === 0) {
            console.log('No data to display');
            const tr = document.createElement('tr');
            const td = document.createElement('td');
            td.colSpan = headers.length;
            td.textContent = '暂无数据';
            td.style.textAlign = 'center';
            tr.appendChild(td);
            tableBody.appendChild(tr);
            return;
        }
        
        // 添加数据行
        data.forEach(row => {
            const tr = document.createElement('tr');
            tr.setAttribute('data-id', row.id);  // 添加 data-id 属性
            
            // 添加基本数据列
            [
                row.id,
                row.name,
                row.level,
                row.gender,
                row.department,
                row.position,
                row.entry_date && row.entry_date !== 'null' && row.entry_date !== '-' ? 
                    new Date(row.entry_date).toLocaleDateString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit'
                    }).replace(/\//g, '-') : '-',
                row.status
            ].forEach((cell, index) => {
                const td = document.createElement('td');
                td.textContent = cell || '-';
                // 只有在非 API 数据时添加双击编辑功能
                if (!isApiData && index > 0) {
                    td.addEventListener('dblclick', () => this.makeEditable(td, row.id, headers[index]));
                }
                tr.appendChild(td);
            });

            // 只有在非 API 数据时添加操作按钮
            if (!isApiData) {
                const actionTd = document.createElement('td');
                actionTd.innerHTML = `
                    <div class="btn-group">
                        <button class="btn btn-sm btn-outline-primary edit-btn" data-id="${row.id}">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${row.id}">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                `;
                tr.appendChild(actionTd);
            }
            
            tableBody.appendChild(tr);
        });

        // 只有在非 API 数据时添加事件监听
        if (!isApiData) {
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const rowId = e.currentTarget.dataset.id;
                    this.showPasswordPrompt(() => this.showEditForm(rowId));
                });
            });

            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const rowId = e.currentTarget.dataset.id;
                    this.showPasswordPrompt(() => this.deleteRecord(rowId));
                });
            });
        }

        // 移除新增按钮（如果是 API 数据或组织分析详情页面）
        if (isApiData || (modalTitle && modalTitle.textContent.includes('组织分析详情'))) {
            const addButton = document.querySelector('.add-btn');
            if (addButton) {
                addButton.remove();
            }
        }
    }

    showAddForm() {
        this.showPasswordPrompt(() => {
            const modalHtml = `
                <div class="modal fade" id="addModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">新增人员</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <form id="addForm">
                                    <div class="mb-3">
                                        <label class="form-label">姓名</label>
                                        <input type="text" class="form-control" name="name" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">职级</label>
                                        <input type="text" class="form-control" name="level">
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">性别</label>
                                        <select class="form-select" name="gender">
                                            <option value="男">男</option>
                                            <option value="女">女</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">员工工号</label>
                                        <input type="text" class="form-control" name="department">
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">职位</label>
                                        <input type="text" class="form-control" name="position">
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">入职日期</label>
                                        <input type="date" class="form-control" name="entry_date" value="${new Date().toISOString().split('T')[0]}">
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">状态</label>
                                        <select class="form-select" name="status">
                                            <option value="在职">在职</option>
                                            <option value="离职">离职</option>
                                            <option value="试用">试用</option>
                                        </select>
                                    </div>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="saveAdd">保存</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);
            const modal = new bootstrap.Modal(document.getElementById('addModal'));
            modal.show();

            document.getElementById('saveAdd').addEventListener('click', () => {
                const formData = new FormData(document.getElementById('addForm'));
                const data = Object.fromEntries(formData.entries());
                this.addRecord(data);
                modal.hide();
            });

            document.getElementById('addModal').addEventListener('hidden.bs.modal', function () {
                this.remove();
            });
        });
    }

    async addRecord(data) {
        try {
            const response = await fetch('/api/db/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                throw new Error('添加失败');
            }

            // 显示成功提示
            this.showToast('添加成功', 'success');
            
            // 刷新数据
            location.reload();
        } catch (error) {
            this.showToast('添加失败: ' + error.message, 'error');
        }
    }

    async deleteRecord(id) {
        const modalHtml = `
            <div class="modal fade" id="deleteConfirmModal" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-body p-4">
                            <div class="text-center mb-4">
                                <div class="delete-icon-wrapper mb-3">
                                    <i class="fas fa-trash-alt text-danger"></i>
                                </div>
                                <h5 class="modal-title mb-2">确认删除</h5>
                                <p class="text-muted mb-0">删除后将无法恢复，是否确认删除？</p>
                            </div>
                            <div class="d-flex justify-content-center gap-2 mt-4">
                                <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">
                                    <i class="fas fa-times me-1"></i>取消
                                </button>
                                <button type="button" class="btn btn-danger px-4 confirm-delete">
                                    <i class="fas fa-check me-1"></i>确认删除
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <style>
                .delete-icon-wrapper {
                    width: 70px;
                    height: 70px;
                    background: rgba(220, 53, 69, 0.1);
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin: 0 auto;
                }
                
                .delete-icon-wrapper i {
                    font-size: 28px;
                }
                
                #deleteConfirmModal .modal-content {
                    border: none;
                    border-radius: 12px;
                    box-shadow: 0 2px 20px rgba(0,0,0,0.1);
                }
                
                #deleteConfirmModal .btn {
                    min-width: 120px;
                    border-radius: 6px;
                    font-weight: 500;
                    transition: all 0.3s ease;
                }
                
                #deleteConfirmModal .btn:hover {
                    transform: translateY(-1px);
                }
                
                #deleteConfirmModal .btn-light {
                    background: #f8f9fa;
                    border-color: #e9ecef;
                }
                
                #deleteConfirmModal .btn-light:hover {
                    background: #e9ecef;
                }
                
                #deleteConfirmModal .btn-danger {
                    background: #dc3545;
                    border-color: #dc3545;
                }
                
                #deleteConfirmModal .btn-danger:hover {
                    background: #c82333;
                    border-color: #bd2130;
                }
                
                .modal-backdrop.show {
                    opacity: 0.7;
                }
                
                @keyframes fadeInUp {
                    from {
                        opacity: 0;
                        transform: translate3d(0, 20px, 0);
                    }
                    to {
                        opacity: 1;
                        transform: translate3d(0, 0, 0);
                    }
                }
                
                #deleteConfirmModal .modal-dialog {
                    animation: fadeInUp 0.3s ease;
                }
            </style>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modalElement = document.getElementById('deleteConfirmModal');
        const modal = new bootstrap.Modal(modalElement);

        return new Promise((resolve) => {
            modalElement.querySelector('.confirm-delete').addEventListener('click', async () => {
                try {
                    const response = await fetch('/api/db/delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id })
                    });

                    const result = await response.json();
                    if (result.success) {
                        modal.hide();
                        
                        // 1. 从表格中移除被删除的行
                        const row = document.querySelector(`tr[data-id="${id}"]`);
                        if (row) {
                            row.remove();
                        }
                        
                        // 2. 检查表格是否为空
                        const tableBody = document.getElementById('table-body');
                        if (tableBody && !tableBody.children.length) {
                            tableBody.innerHTML = '<tr><td colspan="100%" class="text-center">暂无数据</td></tr>';
                        }
                        
                        // 3. 更新所有相关数据显示
                        await this.updateAllData();
                        
                        // 4. 显示成功消息
                        this.showToast('删除成功', 'success');
                        
                        resolve(true);
                    } else {
                        this.showToast(result.error || '删除失败', 'error');
                        resolve(false);
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    this.showToast('系统错误，请稍后重试', 'error');
                    resolve(false);
                }
            });

            modalElement.addEventListener('hidden.bs.modal', () => {
                modalElement.remove();
                resolve(false);
            });

            modal.show();
        });
    }

    // 新增更新所有数据的方法
    async updateAllData() {
        try {
            const loadingToast = this.showToast('正在更新数据...', 'info');
            
            // 1. 更新总人数对比数据
            const totalResponse = await fetch('/api/comparison/total');
            if (!totalResponse.ok) throw new Error('获取总人数数据失败');
            const totalData = await totalResponse.json();
            
            // 确保数据格式正确
            const processedTotalData = {
                api_total: totalData.data?.api_total || 0,
                db_total: totalData.data?.db_total || 0,
                matched: totalData.data?.matched || false,
                api_avg_age: totalData.data?.api_avg_age || 0,
                db_avg_age: totalData.data?.db_avg_age || 0,
                age_matched: totalData.data?.age_matched || false,
                difference: totalData.data?.difference || 0
            };
            
            this.updateTotalComparison(processedTotalData);
            
            // 2. 更新职级分布对比数据
            const rankResponse = await fetch('/api/comparison/rank');
            if (!rankResponse.ok) throw new Error('获取职级分布数据失败');
            const rankData = await rankResponse.json();
            const selectedSeries = document.querySelector('#series-filter')?.value || 'P序列';
            this.updateRankComparison(rankData, selectedSeries);
            
            // 3. 更新统计面板数据
            const statsData = {
                api_total: processedTotalData.api_total,
                db_total: processedTotalData.db_total,
                matched: processedTotalData.matched,
                age_matched: processedTotalData.age_matched,
                rank_data: rankData.data
            };
            this.updateStatsPanel(statsData);
            
            // 移除加载提示
            if (loadingToast) {
                loadingToast.remove();
            }
        } catch (error) {
            console.error('更新数据失败:', error);
            this.showToast('更新数据失败: ' + error.message, 'error');
        }
    }

    // 计算匹配率的辅助方法
    calculateMatchRate(data) {
        if (!data || !data.api_total || !data.db_total) return 0;
        const min = Math.min(data.api_total, data.db_total);
        const max = Math.max(data.api_total, data.db_total);
        return Math.round((min / max) * 100);
    }

    showToast(message, type = 'success') {
        const toastDiv = document.createElement('div');
        toastDiv.className = 'toast position-fixed top-0 end-0 m-3';
        toastDiv.innerHTML = `
            <div class="toast-header bg-${type} text-white">
                <strong class="me-auto">${type === 'success' ? '成功' : '错误'}</strong>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        `;
        document.body.appendChild(toastDiv);
        
        const toast = new bootstrap.Toast(toastDiv, {
            delay: 3000,
            animation: true
        });
        toast.show();

        setTimeout(() => {
            toastDiv.remove();
        }, 3000);
    }

    makeEditable(td, rowId, field) {
        // 先验证密码
        this.showPasswordPrompt(() => {
            const originalValue = td.textContent;
            td.innerHTML = `
                <input type="text" class="form-control form-control-sm" 
                       value="${originalValue}" 
                       style="width: 100%; min-width: 100px;">
            `;
            const input = td.querySelector('input');
            input.focus();
            
            const saveChanges = async () => {
                const newValue = input.value.trim();
                if (newValue !== originalValue) {
                    try {
                        await this.updateData(rowId, field, newValue);
                        td.textContent = newValue || '-';
                    } catch (error) {
                        // 如果更新失败，恢复原值
                        td.textContent = originalValue;
                    }
                } else {
                    td.textContent = originalValue;
                }
            };
            
            input.addEventListener('blur', saveChanges);
            
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    saveChanges();
                }
            });
        });
    }

    showEditForm(rowId) {
        // 获取当前行数据
        const row = document.querySelector(`[data-id="${rowId}"]`).closest('tr');
        const cells = row.cells;
        
        // 处理日期值
        const entryDate = cells[6].textContent;
        let formattedDate = '';
        if (entryDate && entryDate !== '-') {
            try {
                // 尝试解析日期
                const date = new Date(entryDate);
                if (!isNaN(date.getTime())) {
                    formattedDate = date.toISOString().split('T')[0];
                }
            } catch (e) {
                console.error('日期解析失败:', e);
            }
        }
        
        const modalHtml = `
            <div class="modal fade" id="editModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">编辑人员信息</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <form id="editForm">
                                <div class="mb-3">
                                    <label class="form-label">姓名</label>
                                    <input type="text" class="form-control" name="name" value="${cells[1].textContent}">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">职级</label>
                                    <input type="text" class="form-control" name="level" value="${cells[2].textContent}">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">性别</label>
                                    <select class="form-select" name="gender">
                                        <option value="男" ${cells[3].textContent === '男' ? 'selected' : ''}>男</option>
                                        <option value="女" ${cells[3].textContent === '女' ? 'selected' : ''}>女</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">员工工号</label>
                                    <input type="text" class="form-control" name="department" value="${cells[4].textContent}">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">职位</label>
                                    <input type="text" class="form-control" name="position" value="${cells[5].textContent}">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">入职日期</label>
                                    <input type="date" class="form-control" name="entry_date" value="${formattedDate}">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">状态</label>
                                    <select class="form-select" name="status">
                                        <option value="在职" ${cells[7].textContent === '在职' ? 'selected' : ''}>在职</option>
                                        <option value="离职" ${cells[7].textContent === '离职' ? 'selected' : ''}>离职</option>
                                        <option value="试用" ${cells[7].textContent === '试用' ? 'selected' : ''}>试用</option>
                                    </select>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="saveEdit">保存</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modal = new bootstrap.Modal(document.getElementById('editModal'));
        modal.show();

        document.getElementById('saveEdit').addEventListener('click', async () => {
            const form = document.getElementById('editForm');
            const formData = new FormData(form);
            
            // 逐个更新字段
            for (let [field, value] of formData.entries()) {
                if (value !== cells[['name', 'level', 'gender', 'department', 'position', 'entry_date', 'status']
                    .indexOf(field) + 1].textContent) {
                    await this.updateData(rowId, field, value);
                }
            }
            
            modal.hide();
            location.reload();  // 刷新页面以显示更新后的数据
        });

        document.getElementById('editModal').addEventListener('hidden.bs.modal', function () {
            this.remove();
        });
    }

    showPasswordPrompt(callback) {
        const modalHtml = `
            <div class="modal fade" id="passwordModal" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-body p-4">
                            <div class="text-center mb-4">
                                <div class="auth-icon-wrapper mb-3">
                                    <i class="fas fa-shield-alt"></i>
                                </div>
                                <h5 class="modal-title mb-2">安全验证</h5>
                                <p class="text-muted mb-4">请输入管理员密码以继续操作</p>
                            </div>
                            
                            <div class="password-display mb-4">
                                <div class="password-dots d-flex justify-content-center gap-2">
                                </div>
                            </div>

                            <div class="virtual-keyboard">
                                <div class="number-pad mb-3">
                                    ${Array.from({length: 9}, (_, i) => `
                                        <button type="button" class="number-key" data-value="${i + 1}">
                                            ${i + 1}
                                        </button>
                                    `).join('')}
                                    <button type="button" class="number-key" data-value="0">0</button>
                                </div>
                                <div class="action-buttons d-flex gap-2">
                                    <button type="button" class="action-btn clear-btn flex-grow-1">
                                        <i class="fas fa-backspace"></i>
                                    </button>
                                    <button type="button" class="action-btn confirm-btn flex-grow-1">
                                        <i class="fas fa-check me-1"></i>确认
                                    </button>
                                </div>
                            </div>

                            <div class="invalid-feedback text-center mt-3" style="display: none;">
                                <i class="fas fa-exclamation-circle me-1"></i>
                                <span class="error-message"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <style>
                #passwordModal .modal-content {
                    border: none;
                    border-radius: 16px;
                    box-shadow: 0 10px 40px rgba(0,0,0,0.1);
                }

                .auth-icon-wrapper {
                    width: 80px;
                    height: 80px;
                    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin: 0 auto;
                    color: white;
                    font-size: 32px;
                    box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2);
                }

                .password-display {
                    background: #f8fafc;
                    border-radius: 12px;
                    padding: 16px;
                }

                .password-dots {
                    min-height: 24px;
                }

                .password-dot {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                    background-color: #e2e8f0;
                    transition: all 0.2s ease;
                }

                .password-dot.filled {
                    background-color: #6366f1;
                    transform: scale(1.1);
                }

                .virtual-keyboard {
                    background: #f8fafc;
                    border-radius: 12px;
                    padding: 16px;
                }

                .number-pad {
                    display: grid;
                    grid-template-columns: repeat(3, 1fr);
                    gap: 12px;
                    margin-bottom: 12px;
                }

                .number-key {
                    background: white;
                    border: 1px solid #e2e8f0;
                    border-radius: 12px;
                    height: 50px;
                    font-size: 18px;
                    font-weight: 500;
                    color: #1e293b;
                    transition: all 0.2s ease;
                    cursor: pointer;
                }

                .number-key:hover {
                    background: #f1f5f9;
                    transform: translateY(-1px);
                }

                .number-key:active {
                    transform: translateY(1px);
                }

                .action-btn {
                    height: 50px;
                    border-radius: 12px;
                    font-size: 16px;
                    font-weight: 500;
                    transition: all 0.2s ease;
                    border: none;
                }

                .clear-btn {
                    background: #f1f5f9;
                    color: #64748b;
                }

                .clear-btn:hover {
                    background: #e2e8f0;
                }

                .confirm-btn {
                    background: #6366f1;
                    color: white;
                }

                .confirm-btn:hover {
                    background: #4f46e5;
                }

                .confirm-btn:disabled {
                    background: #cbd5e1;
                    cursor: not-allowed;
                }

                .password-dot.shake {
                    animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
                }

                @keyframes shake {
                    10%, 90% { transform: translate3d(-1px, 0, 0); }
                    20%, 80% { transform: translate3d(2px, 0, 0); }
                    30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
                    40%, 60% { transform: translate3d(4px, 0, 0); }
                }

                .invalid-feedback {
                    color: #ef4444;
                    font-size: 0.875rem;
                }

                @keyframes fadeInUp {
                    from {
                        opacity: 0;
                        transform: translate3d(0, 20px, 0);
                    }
                    to {
                        opacity: 1;
                        transform: translate3d(0, 0, 0);
                    }
                }

                #passwordModal .modal-dialog {
                    animation: fadeInUp 0.3s ease;
                }

                .modal-backdrop.show {
                    opacity: 0.2;
                    backdrop-filter: blur(4px);
                }
            </style>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modalElement = document.getElementById('passwordModal');
        const modal = new bootstrap.Modal(modalElement);
        const dotsContainer = modalElement.querySelector('.password-dots');
        const invalidFeedback = modalElement.querySelector('.invalid-feedback');
        const errorMessage = modalElement.querySelector('.error-message');
        let password = '';

        // 更新密码点显示
        const updateDots = () => {
            dotsContainer.innerHTML = '';
            for (let i = 0; i < 6; i++) {
                const dot = document.createElement('div');
                dot.className = `password-dot ${i < password.length ? 'filled' : ''}`;
                dotsContainer.appendChild(dot);
            }
        };

        // 初始化密码点
        updateDots();

        // 处理密码确认
        const handlePasswordConfirm = async () => {
            try {
                const response = await fetch('/api/verify_password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ password })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    modal.hide();
                    if (callback) callback();
                } else {
                    errorMessage.textContent = result.error || '密码错误';
                    invalidFeedback.style.display = 'block';
                    
                    // 添加抖动动画
                    dotsContainer.querySelectorAll('.password-dot').forEach(dot => {
                        dot.classList.add('shake');
                        setTimeout(() => dot.classList.remove('shake'), 500);
                    });
                    
                    // 如果是锁定状态，禁用输入
                    if (result.error && result.error.includes('锁定')) {
                        // 禁用所有按钮
                        modalElement.querySelectorAll('.number-key, .confirm-btn, .clear-btn').forEach(button => {
                            button.disabled = true;
                        });
                        
                        // 显示倒计时
                        const minutes = result.error.match(/\d+/)?.[0] || 0;
                        if (minutes > 0) {
                            startLockoutCountdown(minutes);
                        }
                    }
                    
                    // 清空密码
                    password = '';
                    updateDots();
                }
            } catch (error) {
                console.error('密码验证失败:', error);
                errorMessage.textContent = '系统错误，请稍后重试';
                invalidFeedback.style.display = 'block';
            }
        };

        // 处理数字按键点击
        modalElement.querySelectorAll('.number-key').forEach(button => {
            button.addEventListener('click', () => {
                // 如果按钮被禁用，不处理点击事件
                if (button.disabled) return;
                
                if (password.length < 6) {
                    password += button.dataset.value;
                    updateDots();
                    if (password.length === 6) {
                        handlePasswordConfirm();
                    }
                }
            });
        });

        // 处理清除按钮
        modalElement.querySelector('.clear-btn').addEventListener('click', () => {
            // 如果按钮被禁用，不处理点击事件
            if (modalElement.querySelector('.clear-btn').disabled) return;
            
            if (password.length > 0) {
                password = password.slice(0, -1);
                updateDots();
                invalidFeedback.style.display = 'none';
            }
        });

        // 处理确认按钮
        modalElement.querySelector('.confirm-btn').addEventListener('click', () => {
            // 如果按钮被禁用，不处理点击事件
            if (modalElement.querySelector('.confirm-btn').disabled) return;
            
            handlePasswordConfirm();
        });

        // 添加锁定倒计时功能
        const startLockoutCountdown = (minutes) => {
            let remainingSeconds = minutes * 60;
            const countdownInterval = setInterval(() => {
                remainingSeconds--;
                if (remainingSeconds <= 0) {
                    clearInterval(countdownInterval);
                    // 启用所有按钮
                    modalElement.querySelectorAll('.number-key, .confirm-btn, .clear-btn').forEach(button => {
                        button.disabled = false;
                    });
                    invalidFeedback.style.display = 'none';
                    // 清空密码
                    password = '';
                    updateDots();
                } else {
                    const mins = Math.floor(remainingSeconds / 60);
                    const secs = remainingSeconds % 60;
                    errorMessage.textContent = `账户已锁定，请等待 ${mins}:${secs.toString().padStart(2, '0')} 后重试`;
                }
            }, 1000);
            
            modalElement.dataset.countdownInterval = countdownInterval;
        };

        // 模态框关闭时清理
        modalElement.addEventListener('hidden.bs.modal', function () {
            if (this.dataset.countdownInterval) {
                clearInterval(this.dataset.countdownInterval);
            }
            this.remove();
        });

        modal.show();
    }

    async updateData(rowId, field, value) {
        try {
            console.log('Updating data:', { rowId, field, value });  // 添加日志
            const response = await fetch('/api/db/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    id: rowId,
                    field: field.toLowerCase(),  // 确保字段名小写
                    value: value
                })
            });

            // 检查响应状态
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            
            if (result.success) {
                // 显示成功提示
                this.showToast('更新成功', 'success');
                
                // 可选：刷新数据
                // location.reload();
            } else {
                throw new Error(result.error || '更新失败');
            }
        } catch (error) {
            console.error('更新失败:', error);
            this.showToast('更新失败: ' + error.message, 'error');
            throw error;
        }
    }

    showError(message) {
        const container = this.getElement(this.elements.tableContainer);
        container.style.display = 'block';
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                ${message}
            </div>
        `;
        
        // 隐藏iframe容器
        this.getElement(this.elements.iframeContainer).style.display = 'none';
    }
}